package com.iqilu.ksd.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.MaterialDialog;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.ImageSize;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.ImageUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.muzhi.camerasdk.library.utils.T;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import id.zelory.compressor.Compressor;
import okhttp3.Call;
import okhttp3.Request;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 个人中心页面
 * Created by coofee on 2015/12/9.
 */
public class UserActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    public static String TAG = "UserActivity";

    private LigDialog ligDialog;
    private String picPath = "";
    //    private String oPicPath = "";
    private UserBean user;
    private MyApplication myApplication;

    private TimePickerView pvTime;
    private SimpleDraweeView imgAvatar;
    private EditText etNickname;
    private RadioGroup rgSex;
    private RadioButton rbBoy;
    private RadioButton rbGirl;
    private TextView tvBirthday;
    private Button btLogout;
    private TextView tvTitle;
    private ImageView btLeft;
    private ImageView btRight;

    private static final int CODE_PHOTO = 101;
    private static final int CODE_ALBUM = 102;
    private static final int CODE_CROP = 103;

    private static final int PER_PHOTO = 201;
    private static final int PER_ALBUM = 202;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        myApplication = (MyApplication) getApplication();
        user = myApplication.getUser();
        if (user == null || user.getId() < 1) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        initView();
//        userBean = new UserBean();
//        userBean.setSex(1);
        //时间选择器
        pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        pvTime.setRange(1950, 2050);
        pvTime.setTime(new Date());
        pvTime.setCancelable(true);
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String birthday = format.format(date);
                tvBirthday.setText(birthday);
                user.setBirthday(birthday);
            }
        });
        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == rbBoy.getId()) {
                    user.setSex(1);
                } else {
                    user.setSex(2);
                }
            }
        });
        initHead();
        init();
    }

    private void initView() {
        imgAvatar = getView(R.id.img_avatar);
        etNickname = getView(R.id.et_nickname);
        rgSex = getView(R.id.rg_sex);
        rbBoy = getView(R.id.rb_boy);
        rbGirl = getView(R.id.rb_girl);
        tvBirthday = getView(R.id.tv_birthday);
        btLogout = getView(R.id.bt_logout);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        btLeft = getView(R.id.bt_left);
        btRight = getView(R.id.bt_right);
        imgAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectAvatar();
            }
        });
        tvBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvTime.show();
            }
        });
        btLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLogout();
            }
        });

        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
    }

    public void init() {
        setAvatar();
        etNickname.setText(user.getNickname());
        if (user.getSex() != 2) {
            rbBoy.setChecked(true);
        } else {
            rbGirl.setChecked(true);
        }
        String birthday = user.getBirthday();
        tvBirthday.setText(birthday);
    }

    private void initHead() {
        tvTitle.setText(R.string.user_title);
        btRight.setVisibility(View.VISIBLE);
    }

    private void save() {
        if (TextUtils.isEmpty(etNickname.getText())) {
            Toast.makeText(this, R.string.user_nickname_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        user.setNickname("" + etNickname.getText());
        user.setBirthday("" + tvBirthday.getText());
        saveInfo();
    }

    private void selectAvatar() {
        KeyboardUtils.hideSoftInput(this);
        String str[] = {getString(R.string.user_from_album), getString(R.string.user_from_photo)};
        final ActionSheetDialog dialog = new ActionSheetDialog(this, str, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        selectFromAlbum();
                        break;
                    case 1:
                        selectFromPhoto();
                        break;
                    default:
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    @AfterPermissionGranted(PER_ALBUM)
    private void selectFromAlbum() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, CODE_ALBUM);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_storage), PER_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    @AfterPermissionGranted(PER_PHOTO)
    private void selectFromPhoto() {
        if (EasyPermissions.hasPermissions(this, Manifest.permission.CAMERA)) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            String path = CacheUtils.getCacheDir(this);
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            picPath = path + System.currentTimeMillis() + ".jpg";
//            oPicPath = picPath;
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picPath)));
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, CODE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_camera), PER_PHOTO, Manifest.permission.CAMERA);
        }
    }

    public void setAvatar() {
        Log.i(TAG, "setAvatar:" + user.getAvatar());
        String path = user.getAvatar();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        Uri uri = Uri.parse(path);
        imagePipeline.evictFromCache(uri);
        imgAvatar.setImageURI(Uri.parse(path));
    }

    public void showLogout() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.user_logout_ensure))
                .btnText(getString(R.string.cancel), getString(R.string.ensure))
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        serverLogOut();
                        myApplication.setUser(null);
                        SPUtils.setPref(UserActivity.this, UserInfo.LOGINHASH, "");
                        EventBus.getDefault().post(new ChangeUserInfoEvent());
                        Toast.makeText(UserActivity.this, R.string.user_logout_success, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        finish();
                    }
                }
        );
    }

    private void uploadAvatar(String path) {
        String url = Api.URL_USER_AVATAR;
        File file = new File(path);
        Log.i(TAG, "file.getName():" + file.getName());
        OkHttpUtils
                .post()
                .url(url)
                .tag(this)
                .addFile("filedata", "" + file.getName(), file)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(UserActivity.this, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                        Toast.makeText(UserActivity.this, R.string.user_upload_avatar_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        UserBean data = null;
                        data = JSONUtils.requestDetail(response, "data", UserBean.class);
                        if (data != null && !TextUtils.isEmpty(data.getAvatar())) {
                            myApplication.getUser().setAvatar(data.getAvatar());
                            user = myApplication.getUser();
                            SPUtils.setPref(UserActivity.this, UserInfo.AVATAR, data.getAvatar());
                            setAvatar();
                            EventBus.getDefault().post(new ChangeUserInfoEvent());
                            Toast.makeText(UserActivity.this, R.string.user_upload_avatar_success, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(UserActivity.this, R.string.user_upload_avatar_error, Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }

    private void saveInfo() {
        String url = Api.URL_USER;
        String query = "nickname=" + user.getNickname() + "&sex=" + user.getSex() + "&birthday=" + user.getBirthday();
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(query)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        ligDialog = new LigDialog(UserActivity.this, getString(R.string.waiting));
                        ligDialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ligDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ligDialog.dismiss();
                        int status = 0;
                        UserBean mUser = null;
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            status = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (status == 1) {
                            mUser = JSONUtils.requestDetail(response, "data", UserBean.class);
                            if (mUser != null && mUser.getId() > 0) {
                                myApplication.setUser(user);
                                EventBus.getDefault().post(new ChangeUserInfoEvent());
                                Toast.makeText(UserActivity.this, R.string.user_save_success, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(UserActivity.this, R.string.user_save_error, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(UserActivity.this, R.string.user_save_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    public void serverLogOut() {
        String url = Api.URL_LOGOUT;
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                myApplication.clearCookie();
                EventBus.getDefault().post(new ChangeUserInfoEvent());
            }

            @Override
            public void onResponse(String response, int id) {
                myApplication.clearCookie();
                EventBus.getDefault().post(new ChangeUserInfoEvent());
            }
        });
    }

    class CompressThread extends AsyncTask<Void, Void, Void> {

        private String path;

        public CompressThread(String path) {
            this.path = path;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ligDialog = new LigDialog(UserActivity.this, getString(R.string.waiting));
            ligDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            File compressedImage = new Compressor.Builder(UserActivity.this)
                .setMaxWidth(ImageSize.AVATAR_WIDTH)
                .setMaxHeight(ImageSize.AVATAR_HEIGHT)
                .setQuality(80)
                .setCompressFormat(Bitmap.CompressFormat.JPEG)
                .setDestinationDirectoryPath(CacheUtils.getCompressDir(UserActivity.this))
                .build()
                .compressToFile(new File(path));
            path = compressedImage.getPath();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            ligDialog.dismiss();
            uploadAvatar(path);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        Bitmap bitmap = null;
        Bitmap comBitmap = null;
        if (requestCode == CODE_ALBUM) {
            Uri uri = data.getData();
            ContentResolver resolver = getContentResolver();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bitmap != null) {
                String mName = System.currentTimeMillis() + ".jpg";
                String mPath = CacheUtils.getCacheDir(this) + mName;
                ImageUtils.save(bitmap, mPath, Bitmap.CompressFormat.JPEG);
                Intent intent = new Intent(this, CropActivity.class);
                intent.putExtra("picPath", mPath);
                intent.putExtra("isAvatar", true);
                startActivityForResult(intent, CODE_CROP);
            }
        }
        if (requestCode == CODE_PHOTO) {
            Intent intent = new Intent(this, CropActivity.class);
            intent.putExtra("picPath", picPath);
            intent.putExtra("isAvatar", true);
            startActivityForResult(intent, CODE_CROP);
        }
        if (requestCode == CODE_CROP) {
            String thumb = data.getStringExtra("thumb");
            Log.i(TAG, "thumb=" + thumb);
            new CompressThread(thumb).execute();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        String str = "";
        int code = 0;
        if (requestCode == PER_ALBUM) {
            str = getString(R.string.per_con_storage);
            code = PER_ALBUM;
        } else if (requestCode == PER_PHOTO) {
            str = getString(R.string.per_con_camera);
            code = PER_PHOTO;
        }
        new AppSettingsDialog.Builder(this, str)
                .setTitle(getString(R.string.per_title))
                .setPositiveButton(getString(R.string.setting))
                .setNegativeButton(getString(R.string.cancel), null)
                .setRequestCode(code)
                .build()
                .show();
    }
}
